package com.aiti.lulian.service.newCard;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.constant.NewCardBusinessConstant;
import com.aiti.lulian.dto.newCard.*;
import com.aiti.lulian.entity.CardHolder;
import com.aiti.lulian.entity.CardOperationLog;
import com.aiti.lulian.entity.CardUserCardSetting;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.newCard.*;
import com.aiti.lulian.gxmh.dto.SysUserDto;
import com.aiti.lulian.mapper.CardHolderMapper;
import com.aiti.lulian.mapper.CardOperationLogMapper;
import com.aiti.lulian.mapper.CardUserCardSettingMapper;
import com.aiti.lulian.mapper.LuLianEnterpriseMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.mapper.newCard.*;
import com.aiti.lulian.vo.CardBaseInfoListVo;
import com.aiti.lulian.vo.newCard.CardBaseInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * description:
 * auth fcb
 * date 2025-08-11 16:58
 **/
@Service
@Slf4j
public class CardBusinessService {

    @Autowired
    private CardPersonalBaseInfoService cardPersonalBaseInfoService;
    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;
    @Autowired
    private CardDescriptionService cardDescriptionService;
    @Autowired
    private CardDescriptionMapper cardDescriptionMapper;
    @Autowired
    private CardLinkInfoService cardLinkInfoService;
    @Autowired
    private CardLinkInfoMapper cardLinkInfoMapper;
    @Autowired
    private CardMoreInfoService cardMoreInfoService;
    @Autowired
    private CardMoreInfoMapper cardMoreInfoMapper;
    @Autowired
    private CardPersonalFileInfoService cardPersonalFileInfoService;
    @Autowired
    private CardPersonalFileInfoMapper cardPersonalFileInfoMapper;
    @Autowired
    private CardVideoInfoService cardVideoInfoService;
    @Autowired
    private CardVideoInfoMapper cardVideoInfoMapper;
    @Autowired
    private CardUserCardSettingMapper cardUserCardSettingMapper;
    @Autowired
    private NewCardVersionMapper newCardVersionMapper;
    @Autowired
    private CardOperationLogMapper cardOperationLogMapper;
    @Autowired
    private CardHolderMapper cardHolderMapper;
    @Autowired
    private CardPrivacySettingMapper cardPrivacySettingMapper;
    @Autowired
    private CardAuditMapper cardAuditMapper;
    @Autowired
    private ShowEnterpriseTrialMapper showEnterpriseTrialMapper;
    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;
    @Autowired
    private GxmhSysMapper gxmhSysMapper;

    /**
     * 根据名片信息，查询名片信息
     * @param cardBaseId
     * @return
     */
    public CardInfoDto getCardDetail(String cardBaseId, String curUserId) {
        CardInfoDto result = new CardInfoDto();
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardBaseId);
        if(cardBaseInfo == null) {
            throw new BusinessException("名片不存在");
        }
        // 查询当前名片是否被交换过
        if(StrUtil.isNotBlank(curUserId)) {
            Integer exchangeCount = cardPersonalBaseInfoMapper.queryExchangeCard(curUserId, cardBaseId);
            if(exchangeCount > 0) {
                result.setIsExchange(true);
            }
        }
        if (StrUtil.isNotBlank(cardBaseInfo.getEnterpriseId())) {
            // 企业名片则将企业的 logo 图片地址查出并赋值给 avatar 字段，用于企业端后台头像的显示
            if ("2".equals(cardBaseInfo.getCardVersion())) {
                // 企业试用版
                ShowEnterpriseTrial showEnterpriseTrial = showEnterpriseTrialMapper.selectById(cardBaseInfo.getEnterpriseId());
                if (showEnterpriseTrial != null) {
                    cardBaseInfo.setAvatar(showEnterpriseTrial.getLogo());
                    if (StrUtil.isBlank(cardBaseInfo.getAvatar())) {
                        cardBaseInfo.setAvatar(showEnterpriseTrial.getPic());
                    }
                }
            } else {
                // 企业基础版及以上
                LuLianEnterprise luLianEnterprise = luLianEnterpriseMapper.selectById(cardBaseInfo.getEnterpriseId());
                if (luLianEnterprise != null) {
                    cardBaseInfo.setAvatar(luLianEnterprise.getLogo());
                    if (StrUtil.isBlank(cardBaseInfo.getAvatar())) {
                        cardBaseInfo.setAvatar(luLianEnterprise.getPic());
                    }
                }
            }
        }
        CardBaseInfoDto cardBaseInfoResult = new CardBaseInfoDto();
        BeanUtils.copyProperties(cardBaseInfo, cardBaseInfoResult);
        result.setCardBaseInfo(cardBaseInfoResult);
        // 2. 联系方式
        CardLinkInfo cardLinkInfo = cardLinkInfoMapper.queryByBaseInfoId(cardBaseId);
        if(cardLinkInfo != null) {
            CardLinkDto cardLinkInfoResult = new CardLinkDto();
            BeanUtils.copyProperties(cardLinkInfo, cardLinkInfoResult);
            result.setCardLink(cardLinkInfoResult);
        }
        // 3. 个人介绍和公司介绍
        CardDescription cardDescription = cardDescriptionMapper.queryByBaseInfoId(cardBaseId);
        if(cardDescription != null) {
            CardDescriptionDto cardDescriptionResult = new CardDescriptionDto();
            BeanUtils.copyProperties(cardDescription, cardDescriptionResult);
            result.setCardDescription(cardDescriptionResult);
        }
        // 4. 更多信息
        CardMoreInfo cardMoreInfo = cardMoreInfoMapper.queryByBaseInfoId(cardBaseId);
        if(cardMoreInfo != null) {
            CardMoreInfoDto cardMoreInfoResult = new CardMoreInfoDto();
            BeanUtils.copyProperties(cardMoreInfo, cardMoreInfoResult);
            result.setCardMoreInfo(cardMoreInfoResult);
        }
        // 5. 文件信息
        CardPersonalFileInfo cardPersonalFileInfo = cardPersonalFileInfoMapper.queryByBaseInfoId(cardBaseId);
        if(cardPersonalFileInfo != null) {
            CardFileParamDto cardFileParamDto = new CardFileParamDto();
            cardFileParamDto.setFilePath(cardPersonalFileInfo.getFileUrl());
            cardFileParamDto.setFileName(cardPersonalFileInfo.getFileName());
            cardFileParamDto.setStatus(cardPersonalFileInfo.getStatus());
            cardFileParamDto.setRiskLevel(cardPersonalFileInfo.getRiskLevel());
            result.setCardFile(cardFileParamDto);
        }
        // 6. 视频审核信息
        List<CardVideoInfo> cardVideoList = cardVideoInfoMapper.queryByBaseInfoId(cardBaseId);
        if(CollectionUtils.isNotEmpty(cardVideoList)) {
            List<CardVideoDto> cardVideoDtoList = new ArrayList<>();
            for(CardVideoInfo item : cardVideoList) {
                CardVideoDto cardVideoDto = new CardVideoDto();
                cardVideoDto.setName(item.getVideoName());
                cardVideoDto.setUrl(item.getVideoUrl());
                cardVideoDto.setStatus(item.getStatus());
                cardVideoDto.setRiskLevel(item.getRiskLevel());
                cardVideoDtoList.add(cardVideoDto);
            }
            result.setCardVideoList(cardVideoDtoList);
        }else {
            result.setCardVideoList(new ArrayList<>());
        }
        return result;
    }

    /**
     * 名片会在登录时领取一个，这里相当于更新名片信息
     * 附件文件和视频文件，目前的设计是，只要提交的数据存在这两种文件就去审核，不区分文件是否已经在上次审核通过了
     * @param cardInfoDto
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCardInfo(CardInfoDto cardInfoDto) {
        this.checkParam(cardInfoDto);
        Date now = new Date();
        // 1. 更新基本信息
        CardBaseInfo cardPersonalBaseInfo = new CardBaseInfo();
        BeanUtils.copyProperties(cardInfoDto.getCardBaseInfo(), cardPersonalBaseInfo);
        cardPersonalBaseInfo.setBaseUpdateTime(now);
        cardPersonalBaseInfo.setBaseUpdateBy(cardInfoDto.getUserId());
        cardPersonalBaseInfoMapper.updateCardInfo(cardPersonalBaseInfo);
        // 2. 保存或更新联系方式
        CardLinkDto cardLinkParam = cardInfoDto.getCardLink();
        CardLinkInfo existLinkInfo = cardLinkInfoMapper.queryByBaseInfoId(cardInfoDto.getCardBaseInfo().getBaseId());
        if(existLinkInfo == null) {
            CardLinkInfo cardLinkInfo = new CardLinkInfo();
            BeanUtils.copyProperties(cardLinkParam, cardLinkInfo);
            cardLinkInfo.setBaseId(IdUtil.simpleUUID());
            cardLinkInfo.setBaseInfoId(cardPersonalBaseInfo.getBaseId());
            cardLinkInfoMapper.insert(cardLinkInfo);
        }else {
            existLinkInfo.setMobile(cardLinkParam.getMobile());
            existLinkInfo.setWechat(cardLinkParam.getWechat());
            existLinkInfo.setEmail(cardLinkParam.getEmail());
            existLinkInfo.setAddress(cardLinkParam.getAddress());
            cardLinkInfoMapper.updateCardInfo(existLinkInfo);
        }
        // 3. 保存或更新个人介绍
        CardDescriptionDto cardDescriptionDto = cardInfoDto.getCardDescription();
        if(cardDescriptionDto != null) {
            CardDescription existDescription = cardDescriptionMapper.queryByBaseInfoId(cardPersonalBaseInfo.getBaseId());
            if(existDescription == null) {
                CardDescription cardDescription = new CardDescription();
                BeanUtils.copyProperties(cardDescriptionDto, cardDescription);
                cardDescription.setBaseId(IdUtil.simpleUUID());
                cardDescription.setBaseInfoId(cardPersonalBaseInfo.getBaseId());
                cardDescriptionMapper.insert(cardDescription);
            }else {
                existDescription.setPersonalDescription(cardDescriptionDto.getPersonalDescription());
                existDescription.setEnterpriseDescription(cardDescriptionDto.getEnterpriseDescription());
                cardDescriptionMapper.updateCardInfo(existDescription);
            }

        }
        // 4. 保存或更新更多信息
        CardMoreInfoDto cardMoreInfoDto = cardInfoDto.getCardMoreInfo();
        if(cardMoreInfoDto != null) {
            CardMoreInfo existMoreInfo = cardMoreInfoMapper.queryByBaseInfoId(cardPersonalBaseInfo.getBaseId());
            if(existMoreInfo == null) {
                CardMoreInfo cardMoreInfo = new CardMoreInfo();
                BeanUtils.copyProperties(cardMoreInfoDto, cardMoreInfo);
                cardMoreInfo.setBaseId(IdUtil.simpleUUID());
                cardMoreInfo.setBaseInfoId(cardPersonalBaseInfo.getBaseId());
                cardMoreInfoMapper.insert(cardMoreInfo);
            }else {
                existMoreInfo.setWechatPicPath(cardMoreInfoDto.getWechatPicPath());
                existMoreInfo.setOtherPicPath(cardMoreInfoDto.getOtherPicPath());
                cardMoreInfoMapper.updateCardMoreInfo(existMoreInfo);
            }

        }
        // 5.保存或更新文件
        CardFileParamDto cardFile = cardInfoDto.getCardFile();
        // 删除之前的文件记录
        cardPersonalFileInfoMapper.deleteByBaseInfoId(cardInfoDto.getCardBaseInfo().getBaseId());
        if(cardFile != null) {
            String fileName = cardFile.getFileName();
            String fileId = this.getFileIdByUrl(cardFile.getFilePath());
            CardPersonalFileInfo cardPersonalFileInfo = new CardPersonalFileInfo();
            cardPersonalFileInfo.setBaseId(IdUtil.simpleUUID());
            cardPersonalFileInfo.setBaseInfoId(cardPersonalBaseInfo.getBaseId());
            cardPersonalFileInfo.setFileUrl(cardFile.getFilePath());
            cardPersonalFileInfo.setFileId(fileId);
            cardPersonalFileInfo.setFileName(fileName);
            cardPersonalFileInfo.setFileExt(fileName.substring(fileName.lastIndexOf(".") + 1));
            cardPersonalFileInfo.setStatus(NewCardBusinessConstant.AUDIT_STATUS_2);
            cardPersonalFileInfoMapper.insert(cardPersonalFileInfo);
            // todo 提交审核
        }
        // 6.视频文件
        List<CardVideoDto> cardVideoList = cardInfoDto.getCardVideoList();
        // 删除之前的视频记录
        cardVideoInfoMapper.deleteByBaseInfoId(cardInfoDto.getCardBaseInfo().getBaseId());
        if(CollectionUtil.isNotEmpty(cardVideoList)) {
            List<CardVideoInfo> videoList = new ArrayList<>();
            for (CardVideoDto cardVideoDto : cardVideoList) {
                String url = cardVideoDto.getUrl();
                CardVideoInfo cardVideoInfo = new CardVideoInfo();
                cardVideoInfo.setBaseId(IdUtil.simpleUUID());
                cardVideoInfo.setBaseInfoId(cardPersonalBaseInfo.getBaseId());
                cardVideoInfo.setVideoName(cardVideoDto.getName());
                cardVideoInfo.setVideoUrl(cardVideoDto.getUrl());
                cardVideoInfo.setVideoFullPath(NewCardBusinessConstant.VIDEO_FILE_PATH + this.getFileIdByUrl( url));
                cardVideoInfo.setStatus(NewCardBusinessConstant.AUDIT_STATUS_2);
                videoList.add(cardVideoInfo);
            }
            cardVideoInfoService.saveBatch(videoList);
            // todo 提交审核
        }
    }

    /**
     * 提取文件id
     * @param url
     * @return
     */
    private String getFileIdByUrl(String url) {
        if(StrUtil.isEmpty(url)) {
            return null;
        }
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 删除名片及名片相关的其他信息
     * @param cardBaseId
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeCardInfo(String cardBaseId) {
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardBaseId);
        if(cardBaseInfo == null) {
            throw new BusinessException("名片不存在");
        }
        // 如果删除企业名片，名片不允许删除
        String enterpriseId = cardBaseInfo.getEnterpriseId();
        if(!StringUtils.isEmpty(enterpriseId)){
            throw new BusinessException("该名片是企业名片，请联系企业管理员将该名片移除");
        }

        // 如果个人名片当前正在使用，则不允许删除
        if(StringUtils.isEmpty(enterpriseId) && cardBaseInfo.getCurrentUse() != null && cardBaseInfo.getCurrentUse() == 1) {
            throw new BusinessException("该名片当前正在使用，请先切换名片");
        }
        cardPersonalBaseInfoMapper.removeCardInfo(cardBaseId);
        // todo 删除其他相关信息
    }

    /**
     * 获取名片使用资源类型
     * @param cardId
     * @return
     */
    public Integer getCardUseResourceType(String cardId) {
        return cardPersonalBaseInfoMapper.queryCardUseResourceType(cardId);
    }

    public Message userCards(String userId, String backend) {
        List<CardBaseInfoListVo> cardBaseInfos = cardPersonalBaseInfoMapper.userCardList(userId);
        Map map = new HashMap();
        if(!CollectionUtils.isEmpty(cardBaseInfos)){
            List<CardBaseInfoListVo> enterpriseCardList = cardBaseInfos.stream().filter(f -> !StringUtils.isEmpty(f.getEnterpriseId())).collect(Collectors.toList());
            List<CardBaseInfoListVo> personalCardList = cardBaseInfos.stream().filter(f -> StringUtils.isEmpty(f.getEnterpriseId())).collect(Collectors.toList());
            if("1".equals(backend) && !CollectionUtils.isEmpty(enterpriseCardList)){
                for(int i =enterpriseCardList.size() - 1; i >= 0; i--){
                    CardBaseInfoListVo cardBaseInfoListVo = enterpriseCardList.get(i);
                    String roleId = cardBaseInfoListVo.getRoleId();
                    if(StringUtils.isEmpty(roleId)){
                        enterpriseCardList.remove(i);
                    }

                }
            }
                    
            map.put("enterpriseCard", enterpriseCardList);
            map.put("personalCard", personalCardList);
        }else{
            map.put("enterpriseCard", new ArrayList());
            map.put("personalCard", new ArrayList());
        }
        return Message.success(map);
    }

    public Message queryEnterpriseCardList(String userId){
        List<CardBaseInfo> enterpriseCardList =  cardPersonalBaseInfoMapper.queryEnterpriseCardList(userId);
        return Message.success(enterpriseCardList);
    }

    private void checkParam(CardInfoDto cardInfoDto) {
        CardBaseInfoDto cardBaseInfo = cardInfoDto.getCardBaseInfo();
        if(cardBaseInfo == null) {
            throw new BusinessException("请填写名片基本信息");
        }
        if(StrUtil.isBlank(cardBaseInfo.getBaseId())) {
            throw new BusinessException("名片标识不能为空");
        }
        if(StrUtil.isBlank(cardBaseInfo.getName())) {
            throw new BusinessException("请填写姓名");
        }
        if(StrUtil.isBlank(cardBaseInfo.getEnterpriseName())) {
            throw new BusinessException("请填写公司名称");
        }
        if(StrUtil.isBlank(cardBaseInfo.getPositionOne())) {
            throw new BusinessException("请至少填写一个职位");
        }
        CardLinkDto cardLink = cardInfoDto.getCardLink();
        if(cardLink == null) {
            throw new BusinessException("请填写名片联系方式");
        }
        if(StrUtil.isBlank(cardLink.getMobile())) {
            throw new BusinessException("请填写手机号");
        }
    }


    /**
     * @return 名片ID
     */
    public String createCardBaseInfo(CardBaseInfoDto cardBaseInfoDto) {
        CardBaseInfo cardBaseInfo = new CardBaseInfo();
        BeanUtils.copyProperties(cardBaseInfoDto, cardBaseInfo);
        cardBaseInfo.setBaseId(IdUtil.simpleUUID());
        cardBaseInfo.setBaseCreateBy(cardBaseInfoDto.getUserId());
        cardBaseInfo.setBaseCreateTime(new Date());
        cardBaseInfo.setBaseUpdateBy(cardBaseInfoDto.getUserId());
        // 设置名片的使用的资源类型为--个人免费。该字段会在名片样式保存时进行更新
        cardBaseInfo.setUseResourceType(NewCardBusinessConstant.CARD_USE_RESOURCE_TYPE_1);
        // 查询当前用户是否已拥有过名片
        Integer count = cardPersonalBaseInfoMapper.selectCount(new LambdaQueryWrapper<CardBaseInfo>().eq(CardBaseInfo::getUserId, cardBaseInfoDto.getUserId()).eq(CardBaseInfo::getIsDelete, 0));
        if (count == 0) {
            cardBaseInfo.setCurrentUse(1);
        } else {
            cardBaseInfo.setCurrentUse(0);
        }
        cardPersonalBaseInfoMapper.insert(cardBaseInfo);
        // 设置联系方式，名片所属用户的手机号
        CardLinkInfo cardLinkInfo = new CardLinkInfo();
        cardLinkInfo.setBaseId(IdUtil.simpleUUID());
        cardLinkInfo.setBaseInfoId(cardBaseInfo.getBaseId());
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(cardBaseInfo.getUserId());
        cardLinkInfo.setMobile(sysUserDto.getUsername());
        cardLinkInfoMapper.insert(cardLinkInfo);


        // 创建个人版名片背景
        CardUserCardSetting cardUserCardSetting = new CardUserCardSetting();
        cardUserCardSetting.setUserId(cardBaseInfoDto.getUserId());
        cardUserCardSetting.setCardId(cardBaseInfo.getBaseId());
        cardUserCardSetting.setTemplateId(cardBaseInfoDto.getTemplateId());
        cardUserCardSetting.setBackgroundUrl(cardBaseInfoDto.getPubBackgroundUrl());
        cardUserCardSetting.setForwardCoverUrl(cardBaseInfoDto.getForwardCoverUrl());
        cardUserCardSetting.setCreator(cardBaseInfoDto.getUserId());
        cardUserCardSetting.setBaseCreateTime(new Date());
        cardUserCardSetting.setBaseUpdateTime(new Date());
        cardUserCardSettingMapper.insert(cardUserCardSetting);

        // 创建默认隐私设置
        CardPrivacySetting cardUserCardPrivacySetting = new CardPrivacySetting();
        cardUserCardPrivacySetting.setBaseId(IdUtil.simpleUUID());
        cardUserCardPrivacySetting.setUserId(cardBaseInfoDto.getUserId());
        cardUserCardPrivacySetting.setCardId(cardBaseInfo.getBaseId());
        cardPrivacySettingMapper.insert(cardUserCardPrivacySetting);

        // 设置用户的版本是个人版，这里只设置sys_user.card_version is null 的数据
        newCardVersionMapper.updateUserVersion(cardBaseInfoDto.getUserId(), NewCardBusinessConstant.CARD_VERSION_1, null);
        return cardBaseInfo.getBaseId();
    }

    public CardInfoDto getCardBaseInfo(String cardId, String userId) {
        CardInfoDto result = new CardInfoDto();
        if (StrUtil.isNotBlank(cardId)) {
            CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectOne(new LambdaQueryWrapper<CardBaseInfo>().eq(CardBaseInfo::getBaseId, cardId).eq(CardBaseInfo::getUserId, userId).eq(CardBaseInfo::getIsDelete, 0));
            if (cardBaseInfo != null) {
                CardBaseInfoDto cardBaseInfoResult = new CardBaseInfoDto();
                BeanUtils.copyProperties(cardBaseInfo, cardBaseInfoResult);
                // 设置基本信息
                result.setCardBaseInfo(cardBaseInfoResult);

                CardLinkInfo cardLinkInfo = cardLinkInfoMapper.queryByBaseInfoId(cardId);
                if(cardLinkInfo != null) {
                    CardLinkDto cardLinkInfoResult = new CardLinkDto();
                    BeanUtils.copyProperties(cardLinkInfo, cardLinkInfoResult);
                    // 设置联系方式
                    result.setCardLink(cardLinkInfoResult);
                }
                return result;
            }
        }
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectOne(new LambdaQueryWrapper<CardBaseInfo>().eq(CardBaseInfo::getUserId, userId).eq(CardBaseInfo::getIsDelete, 0).eq(CardBaseInfo::getCurrentUse, 1));
        if (cardBaseInfo == null) {
            return null;
        }
        CardBaseInfoDto cardBaseInfoResult = new CardBaseInfoDto();
        BeanUtils.copyProperties(cardBaseInfo, cardBaseInfoResult);
        // 设置基本信息
        result.setCardBaseInfo(cardBaseInfoResult);

        CardLinkInfo cardLinkInfo = cardLinkInfoMapper.queryByBaseInfoId(cardBaseInfo.getBaseId());
        if(cardLinkInfo != null) {
            CardLinkDto cardLinkInfoResult = new CardLinkDto();
            BeanUtils.copyProperties(cardLinkInfo, cardLinkInfoResult);
            // 设置联系方式
            result.setCardLink(cardLinkInfoResult);
        }
        return result;
    }

    public void updatePicBg(CardBaseInfoDto dto) {
        cardPersonalBaseInfoService.update(new LambdaUpdateWrapper<CardBaseInfo>().eq(CardBaseInfo::getBaseId, dto.getBaseId()).set(CardBaseInfo::getCardPicBg, dto.getCardPicBg())
                .set(CardBaseInfo::getBaseUpdateBy, dto.getUserId()).set(CardBaseInfo::getBaseUpdateTime, new Date()));
    }

    public void updateLoggedIn(String cardId) {
        cardPersonalBaseInfoService.update(new LambdaUpdateWrapper<CardBaseInfo>().eq(CardBaseInfo::getBaseId, cardId).set(CardBaseInfo::getLoggedIn, 1));
    }

    public void updateCurrentUse(String cardId) {
        CardBaseInfo baseInfo = cardPersonalBaseInfoService.getById(cardId);
        if (baseInfo != null) {
            cardPersonalBaseInfoService.update(new LambdaUpdateWrapper<CardBaseInfo>().eq(CardBaseInfo::getUserId, baseInfo.getUserId()).eq(CardBaseInfo::getIsDelete, 0).set(CardBaseInfo::getCurrentUse, 0));
            cardPersonalBaseInfoService.update(new LambdaUpdateWrapper<CardBaseInfo>().eq(CardBaseInfo::getBaseId, cardId).set(CardBaseInfo::getCurrentUse, 1));
        }
    }

    public void increaseShareCount(String cardId) {
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoService.getById(cardId);
        cardPersonalBaseInfoService.update(new LambdaUpdateWrapper<CardBaseInfo>().eq(CardBaseInfo::getBaseId, cardId).set(CardBaseInfo::getShareCount, cardBaseInfo.getShareCount() + 1));
        cardOperationLogMapper.insert(CardOperationLog.builder().userId(cardBaseInfo.getUserId()).cardId(cardId).enterpriseId(cardBaseInfo.getEnterpriseId()).type("1").build());
    }

    public Map<String, Long> getDataStatistics(String cardId) {
        HashMap<String, Long> resultMap = new HashMap<>();
        CardBaseInfo baseInfo = cardPersonalBaseInfoService.getById(cardId);
        if (baseInfo != null) {
            resultMap.put("viewCount", baseInfo.getViewCount());
            resultMap.put("yesterdayCount", baseInfo.getYesterdayCount());
            resultMap.put("toDayCount", baseInfo.getToDayCount());
            resultMap.put("shareCount", baseInfo.getShareCount());
        } else {
            resultMap.put("viewCount", 0L);
            resultMap.put("yesterdayCount", 0L);
            resultMap.put("toDayCount", 0L);
            resultMap.put("shareCount", 0L);
        }
        List<CardHolder> cardHolders = cardHolderMapper.selectList(new QueryWrapper<CardHolder>().select("DISTINCT user_holder_card_id").eq("user_card_id", cardId));
        resultMap.put("collectCount", (long) cardHolders.size());
        return resultMap;
    }

    public Map<String, String> getEnterpriseUsingData(String enterpriseId) {
        Map<String, String> resultMap = cardPersonalBaseInfoMapper.selectEnterpriseUsingData(enterpriseId);
        if (resultMap == null) {
            resultMap = new HashMap<>();
            resultMap.put("openNum", "--");
            resultMap.put("shareNum", "--");
            resultMap.put("viewNum", "--");
            resultMap.put("exchangeNum", "--");
            resultMap.put("collectNum", "--");
        }
        return resultMap;
    }

    public Map<String, String> getEnterpriseCardUsingData(String enterpriseId, String templateId) {
        Map<String, String> resultMap = cardPersonalBaseInfoMapper.selectEnterpriseCardUsingData(enterpriseId, templateId);
        if (resultMap == null) {
            resultMap = new HashMap<>();
            resultMap.put("openNum", "--");
            resultMap.put("shareNum", "--");
            resultMap.put("viewNum", "--");
            resultMap.put("exchangeNum", "--");
            resultMap.put("collectNum", "--");
        }
        return resultMap;
    }

    public Map<String, String> getPersonalUsingData(String cardId) {
        Map<String, String> resultMap = new HashMap<>();
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardId);
        if (cardBaseInfo == null) {
            resultMap.put("shareNum", "--");
            resultMap.put("viewNum", "--");
            resultMap.put("exchangeNum", "--");
            resultMap.put("collectNum", "--");
            return resultMap;
        }
        resultMap = cardPersonalBaseInfoMapper.selectPersonalUsingData(cardBaseInfo.getUserId());
        if (resultMap == null) {
            resultMap.put("shareNum", "--");
            resultMap.put("viewNum", "--");
            resultMap.put("exchangeNum", "--");
            resultMap.put("collectNum", "--");
        }
        return resultMap;
    }

//    public Map<String, String> getPersonalCardUsingData(String templateId, String userId) {
//        Map<String, String> resultMap = cardPersonalBaseInfoMapper.selectPersonalCardUsingData(cardId);
//        if (resultMap == null) {
//            resultMap = new HashMap<>();
//            resultMap.put("shareNum", "--");
//            resultMap.put("viewNum", "--");
//            resultMap.put("exchangeNum", "--");
//            resultMap.put("collectNum", "--");
//        }
//        return resultMap;
//    }

    public Map<String, String> getPersonalCardUsingData(String cardId) {
        Map<String, String> resultMap = cardPersonalBaseInfoMapper.selectPersonalCardUsingData(cardId);
        if (resultMap == null) {
            resultMap = new HashMap<>();
            resultMap.put("shareNum", "--");
            resultMap.put("viewNum", "--");
            resultMap.put("exchangeNum", "--");
            resultMap.put("collectNum", "--");
        }
        return resultMap;
    }

    public Message getPersonalCardDetail(String cardId, String userId) {
        CardBaseInfoVo vo = cardPersonalBaseInfoMapper.selectPersonalCardDetail(cardId, userId);
        if (vo == null) {
            return Message.fail("名片信息失效");
        }
        return Message.success(vo);
    }

    public Map<String, String> getAdminInfoByEnterpriseId(String enterpriseId) {
        Map<String, String> resultMap = cardPersonalBaseInfoMapper.selectAdminInfoByEnterpriseId(enterpriseId);
        if (resultMap == null) {
            resultMap = new HashMap<>();
            resultMap.put("name", "");
            resultMap.put("positionOne", "");
            resultMap.put("username", "");
        }
        return resultMap;
    }


    /**
     * 判断这个名片是不是企业名片，如果是企业名片则判断该名片是否在审核
     * @param cardId
     * @return 是企业名片且在审核返回true，否则返回false
     */
    public Boolean cardIsAuditing(String cardId) {
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(cardId);
        if (cardBaseInfo == null) {
            throw new BusinessException("名片不存在");
        }
        // 是个人名片，返回false
        if(StrUtil.isBlank(cardBaseInfo.getEnterpriseId())) {
            return false;
        }
        CardAudit cardAudit = cardAuditMapper.queryCardAuditInfoByCardId(cardId);
        // 名片正在审核
        if(NewCardBusinessConstant.CARD_STATUS_2.equals(cardAudit.getCardStatus())) {
            return true;
        }
        return false;
    }
}
